package com.reggie.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.category.dao.CategoryDao;
import com.reggie.category.entity.Category;
import com.reggie.category.service.CategoryService;
import com.reggie.configuration.common.Result;
import com.reggie.configuration.common.tableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceimpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    @Autowired
    private CategoryDao dao;

    @Override
    public Category getByID(Long categoryId) {
        return dao.selectById(categoryId);
    }

    /**
     * 分类的分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result<tableList> selectByCondition(Integer page, Integer pageSize) {
        IPage<Category> pageInfo = new Page<>(page == null ? 1 : page, pageSize == null ? 10 : pageSize);

        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(Category::getSort);
        //看来dao没法直接使用LambdaWrapper，会报错
        IPage<Category> result = dao.selectPage(pageInfo, queryWrapper);

        return Result.success(new tableList(result.getRecords(), result.getTotal()));
    }

    /**
     * 判断菜品分类的类名是否被占用
     *
     * @param name
     * @return
     */
    @Override
    public int selectByName(String name) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getName, name);
        List<Category> categories = dao.selectList(queryWrapper);
        return categories.size();
    }

    /**
     * 判断该分类有没有绑定菜品
     *
     * @param id
     * @return
     */
    @Override
    public Result<String> selectByID(Long id) {
        int x = dao.selectByDishId(id);
        int y = dao.selectBySetmealId(id);
        if (x > 0) {
            return Result.error("该分类绑定了菜品");
        }
        if (y > 0) {
            return Result.error("该套餐绑定了菜品");
        }
        dao.deleteById(id);
        return Result.success("删除成功");
    }

    @Override
    public Result<List<Category>> selectByType() {
        List<Category> categoryName = dao.selectByType();
        return Result.success(categoryName);
    }
}
